// pages/first.ts
const app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    security:-1,//0合法，1违法，2审核中，-1未添加图片
    src:"/resources/add_picture.png",
    imgwidth:0,
    imgheight:0,
    imgprowidth:295,
    imgproheight:413,
    selectItems:["从相册选取","拍照选取"],
    selector:"从相册选取",
    imgsize:100,
    imgprosize:200,
    //value:[0],
    self_definition:false,//是否自定义
    maxCanvasW:1300,
    maxCanvasH:1300,
    pickerviewlist:[
    "尺寸比例不变",
    "标准一寸：25mm x 35mm，295px x 413px",
    "小一寸：22mm x 32mm，260px x 378px",
    "大一寸：33mm x 48mm，390px x 567px",
    "标准二寸：35mm x 49mm，413px x 579px",
    "小二寸：35mm x 45mm，413px x 531px",
    "大二寸：35mm x 53mm，413px x 626px",
    "三寸：55mm x 84mm，649px x 991px",
    "四寸：76mm x 102mm，897px x 1204px",
    "结婚登记照：49mm x 35mm，579px x 413px",
    "公考：25mm x 35mm，295px x 413px",
    "教师资格证：41 x 54mm，480px x 640px",
    "考研：41 x 54mm，480px x 640px",
    "电子社保卡：30mm x 37mm，358px x 441px",
    "电子驾照：44mm x 64mm，520px x 756px",
    "身份证(350dpi)：26mm x 32mm，358px x 441px",
    "大学生图像信息采集：41 x 54mm，480px x 640px"
    ],
    widthlist:[295,260,390,413,413,413,649,897,579,295,480,480,358,520,358,480],
    heightlist:[413,378,567,579,531,626,991,1204,413,413,640,640,441,756,441,640]
  },
  radioChange:function(e){
    var value=e.detail.value;
    if (value=="reference"){
      this.setData({
        self_definition:false
      })

    }
    else{
      this.setData({
        self_definition:true//认为此时为自定义尺寸
      })
    }

  },
  imgchange:function(event){
    this.setData({
    imgwidth:event.detail.width,
    imgheight:event.detail.height,
    imgprowidth:event.detail.width,
    imgproheight:event.detail.height
    })
    if (this.data.imgwidth > this.data.maxCanvasW) {
      const ratio =  this.data.maxCanvasW / this.data.imgwidth
      this.setData({
        imgproheight:Math.ceil(this.data.imgheight * ratio),//每次导入图像的时候，默认压缩后图像尺寸与原图一致
        imgprowidth:this.data.maxCanvasW
        })
  }
  if (this.data.imgheight > this.data.maxCanvasH) {
    const ratio =    this.data.maxCanvasH / this.data.imgheight
    this.setData({
      imgprowidth:Math.ceil(this.data.imgwidth * ratio),//每次导入图像的时候，默认压缩后图像尺寸与原图一致
      imgproheight:this.data.maxCanvasH
      })
}

  },
  selectorchange:function(e){
    var i=e.detail.value;
    var value=this.data.selectItems[i];
    
    this.setData({
      selector:value
    })
    var that=this
    if (this.data.selector=="从相册选取"){
      wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album'],
        //sizeType:['compressed'],
        async success(res) {
          console.log('文件路径：',res.tempFiles[0].tempFilePath)
          console.log('文件大小：',res.tempFiles[0].size/1024,'KB')
         // wx.setStorageSync('key',res.tempFiles[0].tempFilePath)
          that.setData({
            imgsize:Math.floor(res.tempFiles[0].size/1024),
            src:res.tempFiles[0].tempFilePath,
            security:2//每次导入图片默认未检测出
          })
          /*
          wx.showToast({
            title: '预处理中请稍后...', //提示的内容
            duration: 3000, //持续的时间
            icon: 'loading', //图标有success、error、loading、none四种
            mask: true //显示透明蒙层 防止触摸穿透
        })*/
          /*************原图预压缩开始******************* */
          var res_tempfile=await that.preZip(res.tempFiles[0].tempFilePath,100,100,40)
          console.log('预压缩图片地址',res_tempfile)
          /*************原图预压缩结束******************* */
          /********云函数安全检测开始*********/
          var res_security=await that.securityDetect(res_tempfile);
          that.setData({
            security:res_security
          })
          /********云函数安全检测开始*********/
        } 
      })
    }
    if (this.data.selector=="拍照选取"){
      wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['camera'],
       // sizeType:['compressed'],
        async success(res) {
          console.log('文件路径：',res.tempFiles[0].tempFilePath)
          console.log('文件大小：',res.tempFiles[0].size)
         // wx.setStorageSync('key',res.tempFiles[0].tempFilePath)
          that.setData({
            imgsize:Math.floor(res.tempFiles[0].size/1024),
            src:res.tempFiles[0].tempFilePath,
            security:2//每次导入图片默认未检测出
          })/*
          wx.showToast({
            title: '预处理中请稍后...', //提示的内容
            duration: 3000, //持续的时间
            icon: 'loading', //图标有success、error、loading、none四种
            mask: true //显示透明蒙层 防止触摸穿透
        })*/
         /*************原图预压缩开始******************* */
         var res_tempfile=await that.preZip(res.tempFiles[0].tempFilePath,100,100,40)
         console.log('预压缩图片地址',res_tempfile)
         /*************原图预压缩结束******************* */
         /********云函数安全检测开始*********/
         var res_security=await that.securityDetect(res_tempfile);
         that.setData({
           security:res_security
         })
         /********云函数安全检测开始*********/
              }
            });  
        }
    },
  sliderchange:function(e){
    //console.log(this.data.imgsize,e.detail.value);
    this.setData({
      imgprosize:Math.floor(e.detail.value)
})
  },
  pickerviewchange:function(e){
    var v=e.detail.value;
    if (v[0]>0 && v[0]<=16 && this.data.self_definition==false) {//为参考尺寸且已有滚动选择值
    this.setData({
      imgprowidth:this.data.widthlist[v[0]-1],
      imgproheight:this.data.heightlist[v[0]-1],
      //self_definition:true
    })}
    if (v[0]==0 && this.data.self_definition==false){//为参考尺寸且为尺寸不变
     // var that=this
      /*this.setData({
        imgproheight:this.data.imgheight>this.data.maxCanvasH?this.data.maxCanvasH:this.data.imgheight,
        imgprowidth:this.data.imgwidth>this.data.maxCanvasW?this.data.maxCanvasW:this.data.imgwidth,
        //self_definition:true
      })*/
      if (this.data.imgwidth > this.data.maxCanvasW) {
        const ratio =  this.data.maxCanvasW / this.data.imgwidth
        this.setData({
          imgproheight:Math.ceil(this.data.imgheight * ratio),//每次导入图像的时候，默认压缩后图像尺寸与原图一致
          imgprowidth:this.data.maxCanvasW
          })
    }
      if (this.data.imgheight > this.data.maxCanvasH) {
        const ratio =    this.data.maxCanvasH / this.data.imgheight
        this.setData({
          imgprowidth:Math.ceil(this.data.imgwidth * ratio),//每次导入图像的时候，默认压缩后图像尺寸与原图一致
          imgproheight:this.data.maxCanvasH
          })
    }
      }
  },
  selfwidth_confirm:function(e){
    if (this.data.self_definition==true) {//若为自定义则使用该input值作为尺寸
    this.setData({
      imgprowidth:e.detail.value>this.data.maxCanvasW?this.data.maxCanvasW:e.detail.value
    })
  }
  },
  selfheight_confirm:function(e){
    if (this.data.self_definition==true) {//若为自定义则使用该input值作为尺寸
    this.setData({
      imgproheight:e.detail.value>this.data.maxCanvasH?this.data.maxCanvasH:e.detail.value
    })
  }
  },
  
  onTapButton:function(e){
    var that=this;
    //console.log("内存中access_token为：",wx.getStorageSync('access_token'))
    if (that.data.security==0){//确认安全就跳转
    wx.navigateTo({
      url:'/pages/second/second?imgprosize='+that.data.imgprosize+'&imgproheight='+that.data.imgproheight+'&imgprowidth='+that.data.imgprowidth+'&imgsrc='+that.data.src+'&imgsize='+that.data.imgsize+'&maxCanvasH='+that.data.maxCanvasH+'&maxCanvasW='+that.data.maxCanvasW
})
    }
    else if (that.data.security==1){
      wx.showToast({
        title: '违规图片请重选', //提示的内容
        duration: 2000, //持续的时间
        icon: 'error', //图标有success、error、loading、none四种
        mask: true //显示透明蒙层 防止触摸穿透
    })
    }
    else if (that.data.security==2){
      wx.showToast({
        title: '安全审核请重试', //提示的内容
        duration: 2000, //持续的时间
        icon: 'loading', //图标有success、error、loading、none四种
        mask: true //显示透明蒙层 防止触摸穿透
    })
    }
    else if (that.data.security==-1){
      wx.showToast({
        title: '请点击添加图片', //提示的内容
        duration: 2000, //持续的时间
        icon: 'none', //图标有success、error、loading、none四种
        mask: true //显示透明蒙层 防止触摸穿透
    })
    }
  },
  compressimage:function(tempfile,quality){
    return new Promise<string>((resolve, reject) => {
      wx.compressImage({
        src: tempfile, // 图片路径
        quality: quality ,// 压缩质量
        success(res){
          //console.log("缩放又压缩后临时文件地址",res.tempFilePath); // 生成临时文件路径
          resolve(res.tempFilePath);
         // console.log(res.tempFilePath)
          reject(tempfile);
        }
      });
    })

  },
  getfilesize:function(tempfile){
    return new Promise<number>((resolve, reject) => {
      wx.getFileSystemManager().getFileInfo(
        {
          filePath:tempfile,
            success(res)
          {
            let imagesize=Math.ceil(res.size/1024);
            //console.log("getfileinfo ing..此时临时文件大小为",imagesize,"KB")
            resolve(imagesize)
          },
          fail(res){
            console.log("getfileinfo error",res)
          }
        })
    })

  },
  preZip:async function(tmp_src,tmp_imgprowidth,tmp_imgproheight,tmp_imgprosize){//依次为原图地址，期待宽度，期待高度，期待大小
    return new Promise<string>((resolve, reject) => {
      console.log('***********图像预压缩开始*****************')
    var that=this;
    wx.getImageInfo({
      src: tmp_src,
      success: function (e2) {
        const imgW = e2.width;
        const imgH = e2.height;
        var dimgW = tmp_imgprowidth;
        var dimgH = tmp_imgproheight;
        const maxWidth=that.data.maxCanvasW;//设置最大分辨率
        const maxHeight=that.data.maxCanvasH;
        if (dimgW > maxWidth) {
          const ratio = maxWidth / dimgW
          dimgW = maxWidth
          dimgH = dimgH * ratio
      }
      if (dimgH > maxHeight) {
          const ratio = maxHeight / dimgH
          dimgW = dimgW * ratio
          dimgH = maxHeight
      }

       const dpr = wx.getSystemInfoSync().pixelRatio ;//影响清晰程度

        
       /* that.setData({//获取原图宽，高
          imgheight:e2.height,
          imgwidth:e2.width
        })*/
        const query = wx.createSelectorQuery();
        query.select('#avatarCanvas').fields({
              node: true,
              size: true
            }).exec(e3 => {
              console.log('获取画布：', e3);
              const canvas = e3[0].node;
              canvas.width=dimgW*dpr;
              canvas.height=dimgH*dpr;
              
              console.log("imgW,imgH:",imgW,imgH);
              console.log("dimgW,dimgH:",dimgW,dimgH);
              console.log("canvasW,canvasH:",canvas.width,canvas.height);
              
              const ctx = canvas.getContext('2d');
              ctx.scale(dpr,dpr);//按比例缩放
              ctx.clearRect(0, 0, dimgW,dimgH);//清空画布
              const img = canvas.createImage();//使用在线画布新建图像
              img.src=tmp_src;

              console.log("原图地址为",tmp_src)
              console.log("待加载图片为",img)

              img.onload = async () => 
              {
                console.log('原图已加载完成，下一步将原图绘制在画布上');
   
               ctx.drawImage(img, 0, 0,dimgW,dimgH);//将原图绘制在画布上

                await new Promise(resolve => {
                  setTimeout(() => resolve(""), 50);
                });
                
                wx.canvasToTempFilePath({
                  //offcanvas,//使用离线画布的内容保存临时文件
                  canvas,
                  x: 0,
                  y: 0,
                  destWidth: dimgW,
                  destHeight: dimgH,
                  fileType:"jpg",
                  quality:1,
                  async success(res) 
                  {
                         
                         //console.log("缩放后临时文件地址：",res.tempFilePath); 
                         let tempfile=res.tempFilePath;//原图
                         let tempfile1=tempfile;//压缩后的图，初始化为原图
                         let imagesize=await that.getfilesize(tempfile1)//初次测量原图
                        
                        console.log("要求文件大小为",tmp_imgprosize,"KB，此时临时文件大小为",imagesize,"KB")
                        let times=1
                        while (imagesize >tmp_imgprosize && times>0){

                          console.log("第",times,"次压缩:")
                          
                          tempfile1=await that.compressimage(tempfile,times);
                          times-=1
                        
                          imagesize=await that.getfilesize(tempfile1)
                          console.log("要求文件大小为",tmp_imgprosize,"KB，此时临时文件大小为",imagesize,"KB")
                          
                          }

                        console.log("最终图像地址为:",tempfile1)
                        
                       console.log('***********图像预压缩结束*****************')
                        resolve(tempfile1)
                        reject('SomthingWrong.jpg')
                      
                        }
                      })
                        
                   }
                })
              }
              

            });
          })
          
      },
    
  securityDetect:async function(res_tempfile){//为原图地址
    return new Promise<number>((resolve, reject) => {
      console.log('********云函数安全检测开始*********')
       var contentType="image/"+res_tempfile.split('.')[1];
       var that=this;
           
       //var contentType="image/jpg";
       const fsm = wx.getFileSystemManager();
            fsm.readFile({
              filePath:res_tempfile,//将预压缩图像喂给云函数做检测
              success: function (res) {
                console.log('读取文件结果',res)
                try{
                wx.cloud.init({
                  env:'cloud-9ged6fbx14ed7c19'
                });
                console.log('初始化已完成，开始检测')
                wx.cloud.callFunction({
                  name: 'checkImg2',
                  data: {
                    contentType: contentType,
                    arrayBuffer: res.data
                  },
                  success: function (res) {
                    var srcTips = "正在安全检测中"
                    
                    console.log('安全检测结果res.result:',res.result)
                    console.log('安全检测结果号res.result.errcode:',res.result.errCode)
                    if (res.result.errCode == 0) {
                      srcTips= "合法图片"
                      resolve(0)
 
                    } 
                    else {
                      srcTips= "违法图片"
                      resolve(1)
                    }
                    console.log("srcTips", srcTips)   
                    console.log('********云函数安全检测结束*********')                                   
                  },
                  fail: function (e) {
                    var srcTips= "检测接口异常，请再次提交";
                    resolve(2)
                    console.log("srcTips", srcTips)
                    wx.hideLoading()
                    console.log('********云函数安全检测结束*********')
                  }
                })
              }catch(err){
                console.log('imgSecCheck没执行')
                reject(2)
                console.log('********云函数安全检测结束*********')
              }
            }
          });  
      
           /********云函数安全检测结束*********/
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  go_update(){
    this.setData({
      src:"/resources/add_picture.png"
    })
  },
  onShow() {
    

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})